<template>
  <div class='container'>
    <!-- <button @click="getBtn">获取列表资料</button> -->
    <el-card class="box-card">
      <div
        slot="header"
        class="clearfix"
      >
        <span>试题录入</span>
      </div>
      <!-- 表单 -->
      <div>
        <el-form
          ref="roleFormRef"
          :model="formData"
          :rules="rules"
          size="medium"
          label-width="100px"
        >
          <!-- 学科  -->
          <el-form-item
            label="学科"
            prop="subjectID"
          >
            <el-select
              v-model="formData.subjectID"
              placeholder="请选择下拉选择学科"
              clearable
              :style="{width: '50%'}"
              @change="subChange"
            >
              <el-option
                v-for="(item, index) in subjectList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item
            label="目录"
            prop="catalogID"
          >
            <el-select
              v-model="formData.catalogID"
              placeholder="请选择目录"
              clearable
              :style="{width: '50%'}"
            >
              <el-option
                v-for="(item, index) in cateList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item
            label="企业"
            prop="enterpriseID"
          >
            <el-select
              v-model="formData.enterpriseID"
              placeholder="请选择企业"
              clearable
              :style="{width: '50%'}"
            >
              <el-option
                v-for="(item, index) in enterpriseIDOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 区域 -->
          <!-- <el-row
            flex
            justify="center"
          > -->
          <!-- 城市 -->
          <el-form-item
            label="城市"
            prop="province"
          >
            <!-- 选择城市 -->
            <el-select
              v-model="formData.province"
              placeholder="请选择"
              clearable
              @change="provinceChange"
              :style="{width: '25%'}"
            >
              <el-option
                v-for="(item, index) in provinceOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <!-- 选择区域 -->
            <el-select
              v-model="formData.city"
              placeholder="请选择"
              clearable
              :style="{width: '25%'}"
            >
              <el-option
                v-for="(item, index) in cityOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- </el-col> -->
          <!-- 方向 -->
          <el-form-item
            label="方向"
            prop="direction"
          >
            <el-select
              v-model="formData.direction"
              placeholder="请选择方向"
              clearable
              :style="{width: '50%'}"
            >
              <el-option
                v-for="(item, index) in directionOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item
            label="题型"
            prop="questionType"
          >
            <el-radio-group
              v-model="formData.questionType"
              size="medium"
            >
              <el-radio
                v-for="(item, index) in questionType"
                :key="index"
                :label="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item
            label="难度"
            prop="difficulty"
          >
            <el-radio-group
              v-model="formData.difficulty"
              size="medium"
            >
              <el-radio
                v-for="(item, index) in difficulty"
                :key="index"
                :label="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item
            label="题干"
            prop="question"
          >
            <template>
              <div class="local-quill-editor">
                <quill-editor
                  ref="myLQuillEditor"
                  v-model="formData.question"
                  :options="editorOption"
                  class="editor"
                >
                  <!-- @blur="onEditorBlur"
                  @focus="onEditorFocus"
                  @change="onEditorChange" -->
                </quill-editor>
              </div>
            </template>
          </el-form-item>
          <!-- 单选 -->
          <el-form-item
            v-if="formData.questionType === 1"
            label="选项"
            prop="options"
          >
            <el-row
              v-for="(item,index) in optionsOptions"
              :key="index"
            >
              <el-radio-group
                v-model="optList[0]"
                size="medium"
              >
                <el-radio
                  :label="item.code"
                  @change="singleCheck"
                >{{item.code}}</el-radio>
                <el-input
                  :style="{width: '50%'}"
                  v-model="item.title"
                ></el-input>
                <el-upload
                  id="imgUpload"
                  v-model="item.img"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img
                    width="100%"
                    :src="dialogImageUrl"
                    alt=""
                  >
                </el-dialog>
              </el-radio-group>
            </el-row>
          </el-form-item>
          <!-- 多选 -->
          <el-form-item
            v-else-if="formData.questionType === 2"
            label="选项"
            prop="options"
          >
            <el-row
              v-for="(item,index) in optionsOptions"
              :key="index"
            >
              <!-- optList是正确答案的集合 -->
              <el-checkbox-group
                v-model="optList"
                size="medium"
              >
                <el-checkbox
                  :label="item.code"
                  @change="singleCheck"
                >{{item.code}}</el-checkbox>
                <el-input
                  :style="{width: '50%'}"
                  v-model="item.title"
                ></el-input>
                <el-upload
                  id="imgUpload"
                  v-model="item.img"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img
                    width="100%"
                    :src="dialogImageUrl"
                    alt=""
                  >
                </el-dialog>
              </el-checkbox-group>
            </el-row>
          </el-form-item>
          <!-- 按钮 -->
          <el-button
            type="danger"
            class="addOption"
            :disabled="formData.questionType != 2"
            v-if="formData.questionType != 3"
            @click="addOption"
          >+添加选项和答案</el-button>
          <!-- 解析视频 -->
          <el-form-item
            label="解析视频"
            prop="videoURL"
          >
            <el-input
              v-model="formData.videoURL"
              placeholder="请输入解析视频"
              clearable
              :style="{width: '50%'}"
            >
            </el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item
            label="答案解析"
            prop="answer"
          >
            <template>
              <div class="local-quill-editor">
                <quill-editor
                  ref="myLQuillEditor"
                  v-model="formData.answer"
                  :options="editorOption"
                  class="editor"
                >
                </quill-editor>
              </div>
            </template>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item
            label="题目备注"
            prop="remarks"
          >
            <el-input
              v-model="formData.remarks"
              type="textarea"
              placeholder="请输入题目备注"
              :autosize="{minRows: 4, maxRows: 4}"
              :style="{width: '50%'}"
            ></el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item
            label="试题标签"
            prop="tags"
          >
            <el-select
              v-model="formData.tags"
              placeholder="请选择试题标签"
              clearable
              :multiple="true"
              :style="{width: '50%'}"
            >
              <el-option
                v-for="(item, index) in tagsOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 提交按钮 -->
          <el-form-item size="large">
            <el-button
              type="primary"
              @click="submitForm"
            >确认提交</el-button>
          </el-form-item>
        </el-form>
      </div>

    </el-card>
  </div>
</template>

<script>
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, difficulty, questionType } from '@/api/hmmm/constants'
// import { list } from '@/api/hmmm/subjects'
import { add, detail } from '@/api/hmmm/questions'
import { simple } from '@/api/hmmm/tags'
import { simple as subSimple } from '@/api/hmmm/subjects'
import { simple as cateSimple, list as cateList } from '@/api/hmmm/directorys'
import { list as companyList } from '@/api/hmmm/companys'

// 引入样式和quillEditor
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 工具栏配置项
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  [{ header: 1 }, { header: 2 }],
  [{ list: 'ordered' }, { list: 'bullet' }],
  ['link', 'image']
]
export default {
  components: { quillEditor },
  props: [],
  data () {
    return {
      // 凌晨
      // 学科列表
      subjectList: [],
      // 学科目录
      cateList: [],
      // 企业目录
      enterpriseIDOptions: [],
      // 晚自习
      // tmpList: [],
      // 定义一个临时的fromdata 用于数据回显防止闪动
      tempFormData: {},
      subTotal: undefined,
      cataTotal: undefined,
      // 学科id
      subId: undefined,
      cateId: undefined,
      compId: undefined,
      // 学科名和id的映照
      // subjectList: [],
      // cateList: [],
      cpyList: [],
      // pagesize
      requestParameters: {
        page: 1,
        pagesize: 12
        // username: this.username
      },
      // pagesize
      requestCateParams: {
        pagesize: 10,
        subjectID: ''
      },
      // 选项数据
      optList: [],
      // 表单数据
      formData: {
        subjectID: undefined,
        catalogID: undefined,
        enterpriseID: undefined,
        province: undefined,
        city: undefined,
        direction: undefined,
        questionType: 1,
        difficulty: 1,
        question: undefined,
        videoURL: undefined,
        answer: undefined,
        remarks: undefined,
        tags: undefined,
        // options: 'A'
        options: []
      },
      // 表单校验
      rules: {
        subjectID: [{
          required: true,
          message: '请选择下拉选择学科',
          trigger: 'change'
        }],
        catalogID: [{
          required: true,
          message: '请选择目录',
          trigger: 'change'
        }],
        enterpriseID: [{
          required: true,
          message: '请选择企业',
          trigger: 'change'
        }],
        province: [{
          required: true,
          message: '请选择城市',
          trigger: 'change'
        }],
        direction: [{
          required: true,
          message: '请选择方向',
          trigger: 'change'
        }],
        questionType: [{
          required: true,
          message: '题型不能为空',
          trigger: 'change'
        }],
        difficulty: [{
          required: true,
          message: '难度不能为空',
          trigger: 'change'
        }],
        question: [{
          required: true,
          message: '请输入题干',
          trigger: 'blur'
        }],
        videoURL: [],
        answer: [{
          required: true,
          message: '请输入答案解析',
          trigger: 'blur'
        }],
        remarks: [],
        tags: [],
        options: []
      },
      provinceOptions: [],
      cityOptions: [],
      directionOptions: direction,
      questionType,
      difficulty,
      tagsOptions: [],
      optionsOptions: [{
        code: 'A',
        title: '',
        img: '',
        isRight: 0
      }, {
        code: 'B',
        title: '',
        img: '',
        isRight: 0
      }, {
        code: 'C',
        title: '',
        img: '',
        isRight: 0
      }, {
        code: 'D',
        title: '',
        img: '',
        isRight: 0
      }],
      optLabel: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'],
      // 富文本框
      content: '',
      editorOption: {
        modules: {
          toolbar: toolbarOptions
        },
        theme: 'snow',
        placeholder: '请输入'
        // Some Quill optiosn...
      },
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  computed: {},
  watch: {},
  created () {
    // 判断是否是修改页面
    if (this.$route.query.id) {
      // 调用一个数据回显的函数
      this.showData()
    }
    // 初始化城市数据
    this.provinceOptions = provinces()
    // 获取学科名
    this.getSubName()
    // 获取企业列表
    this.getCompanyList()
    // 获取标签列表
    this.getTagList()
  },
  mounted () {
    this.test()
  },
  methods: {
    // 数据回显
    async showData () {
      console.log('a' + this.optList)
      const { data } = await detail({ id: this.$route.query.id })
      console.log(data)
      // 让目录显示
      this.subChange()
      // 让data里面的题型和难度从字符串变成数字型
      data.questionType = Number(data.questionType)
      data.difficulty = Number(data.difficulty)
      data.tags = Array(data.tags)
      // 赋值
      // this.optionsOptions =
      console.log('++++++++++++++++++++++++++')
      this.optionsOptions = data.options
      console.log('1', data.options)
      console.log('2', this.optionsOptions)
      this.editCheck()
      // this.singleCheck()
      // 回显判断正确答案
      this.formData = data
      // console.log(data)
    },
    async test () {
      const { data } = await detail({ id: 25 })
      console.log(data)
    },
    // 新增时 选项的单选发生变化时
    singleCheck () {
      this.optionsOptions.forEach(e => {
        e.isRight = 0
        // 如果答案列表中有这个选项，那么就改为ture
        if (this.optList.includes(e.code)) {
          e.isRight = 1
        }
      })
    },
    // 编辑时选项对应数据回显
    editCheck () {
      // 首先遍历optionsOptions得到正确答案optList
      this.optionsOptions.forEach(t => {
        if (t.isRight) {
          this.optList.push(t.code)
        }
      })
      console.log(3, this.optList)
    },
    // 提交表单
    submitForm () {
      // 验证表单
      this.$refs.roleFormRef.validate(async valid => {
        if (valid) {
          // 将标签的数据数据转换为字符串
          this.formData.tags = this.formData.tags.join()
          this.formData.difficulty = String(this.formData.difficulty)
          this.formData.questionType = String(this.formData.questionType)
          // 提交表单
          await add({ ...this.formData, options: this.optionsOptions })
          this.$message.success('添加成功')
          // 跳转到基础题库
          this.$router.push('/questions/list')
        }
      })
    },
    // 数据回显++++++++++++
    // 获取id对应的学科名
    async getSName () {
      // console.log(this.subjectList)
      // console.log(111)
      console.log(this.subjectList.filter(t => t.id === '16'))
      // const res = await this.getSubName()
      // console.log(this.tmpList)
      // res.forEach(t => console.log(t))
      // this.subjectList.forEach(t => {
      //   console.log(t)
      //   // console.log('ggggggggggGETNAME' + t.id + this.formData.subjectID)
      //   // if (t.id === this.formData.subjectID) {
      //   //   this.tempFormData.subjectID = t.subjectName
      //   // }
      // })
    },
    // 获取id对应的目录名
    getCName () {
      this.cateList.forEach(t => {
        if (t.directoryName === this.formData.catalogID) {
          this.cateId = t.id
        }
      })
    },
    // 获取学科列表
    async getSubName () {
      // 拿到学科 ID 对应的数据 存储起来
      const { data } = await subSimple()
      this.subjectList = data
    },
    // 当学科列表变化 获取学科目录
    async subChange () {
      // 先清空cateList
      this.cateList = []
      // 得到总数
      const { data } = await cateList()
      const totol = data.counts
      const res = await cateList({ pagesize: totol })
      // 筛选对应的学科下的目录
      res.data.items.forEach(t => {
        if (t.subjectID === this.formData.subjectID) {
          this.cateList.push({ label: t.directoryName, value: t.id })
        }
      })
    },
    // 获取企业列表
    async getCompanyList () {
      const { data } = await companyList()
      const totol = data.counts
      const res = await companyList({ pagesize: totol })
      res.data.items.forEach(t => {
        this.enterpriseIDOptions.push({ label: t.shortName, value: t.id })
      })
    },
    // 初始化城市 区域数据
    provinceChange () {
      // console.log(123)
      this.cityOptions = citys(this.formData.province)
    },
    // 获取标签列表
    async getTagList () {
      const { data } = await simple()
      const totol = data.counts
      const res = await simple({ pagesize: totol })
      this.tagsOptions = res.data
    },
    // 多选添加选项
    addOption () {
      if (this.optionsOptions.length < 11) {
        this.optionsOptions.push({
          code: this.optLabel[this.optionsOptions.length],
          title: '',
          img: '',
          isRight: 0
        })
      } else {
        this.$message.warning('添加选项已达上限')
      }
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" >
.container {
  padding: 20px;
}
.editor {
  padding-bottom: 50px;
  height: 250px;
}
.ql-snow {
  overflow: hidden;
}
.el-radio-group,
.el-checkbox-group {
  line-height: 80px;
  #imgUpload {
    display: inline-block;
    width: 80px;
    .el-upload--picture-card {
      margin-left: 10px;
      width: 80px;
      height: 60px;
      line-height: 80px;
      // vertical-align: top;
    }
  }
}
.addOption {
  // margin-left: 100px;
  margin: 0 0 20px 100px;
  // margin-bottom: 10px;
}
</style>
